package com.ruoyi.user.model.factory;

import com.ruoyi.common.core.enums.ResultEnum;
import com.ruoyi.common.core.exception.base.exception.BaseRuntimeException;
import com.ruoyi.user.model.enums.LoginStrategy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@Component
public class LoginStrategyContext {
    private final static Map<LoginStrategy,LoginFactory> map = new HashMap<>();

    @Autowired
    public void init(List<LoginFactory> loginFactories){
        loginFactories.forEach(v->map.put(v.getStrategy(),v));
    }

    /**
     * 策略获取登录方式
     * @param loginStrategy 登录类型
     * @return 登录策略
     */
    public static LoginFactory getFactory(LoginStrategy loginStrategy){
        return Optional.ofNullable(map.get(loginStrategy))
                .orElseThrow(
                        ()->new BaseRuntimeException(ResultEnum.FAIL_STRATEGY)
                );
    }
}
